﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Lyh.Train.Controls.ListView
{
    public partial class DragableCheckedListBox : CheckedListBox
    {
        public DragableCheckedListBox()
        {
            InitializeComponent();
        }

        public DragableCheckedListBox(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            var index = SelectedIndex;
            if (SelectedItem == null || e.Button != MouseButtons.Left || e.Clicks == 2) return;
            DoDragDrop(SelectedItem, DragDropEffects.All);
            this.SetItemChecked(index, !GetItemChecked(index));
        }

        protected override void OnDragOver(DragEventArgs drgevent)
        {
            base.OnDragOver(drgevent);
            drgevent.Effect = DragDropEffects.Move;
        }

        protected override void OnDragDrop(DragEventArgs drgevent)
        {
            base.OnDragDrop(drgevent);
            var index = IndexFromPoint(PointToClient(new Point(drgevent.X, drgevent.Y)));
            var item = SelectedItem;
            Items.Remove(item);
            if (index < 0) Items.Add(item);
            else Items.Insert(index, item);
        }

    }
}